package com.yxp.offer;

import com.yxp.middle.Problem1008;
import com.yxp.util.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author : yang.xp
 * @date : 2021/8/18 15:02
 * @description : 剑指 Offer 32 - II. 从上到下打印二叉树 II
 * 从上到下按层打印二叉树，同一层的节点按从左到右的顺序打印，每一层打印到一行。
 */
public class Problem32_2 {

    public static void main(String[] args) {
        int[] numbers = new int[]{8, 5, 1, 7, 10, 12};
        Problem1008 problem1008 = new Problem1008();
        TreeNode treeNode = problem1008.bstFromPreorder(numbers);
        Problem32_2 problem32_2 = new Problem32_2();
        System.out.println(problem32_2.levelOrder(treeNode));
    }

    // 应该是属于广度优先 bfs
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        Queue<TreeNode> nodeQueue = new LinkedList<>();
        nodeQueue.add(root);
        List<List<Integer>> resultList = new ArrayList<>();
        while (!nodeQueue.isEmpty()) {
            List<Integer> integers = addFlow(nodeQueue);
            if (!integers.isEmpty()) {
                resultList.add(integers);
            } else {
                break;
            }
        }
        return resultList;
    }

    // 把一层元素都添加到这个里面
    public List<Integer> addFlow(Queue<TreeNode> treeNodes) {
        if (treeNodes.isEmpty()) {
            return new ArrayList<>();
        }
        List<Integer> resultList = new ArrayList<>();// 本层的所有元素
        Queue<TreeNode> treeNodeQueue = new LinkedList<>();//收集下一层
        while (!treeNodes.isEmpty()) {
            TreeNode poll = treeNodes.poll();
            if (poll == null) {
                continue;
            }
            if (poll.left != null) {
                treeNodeQueue.add(poll.left);
            }
            if (poll.right != null) {
                treeNodeQueue.add(poll.right);
            }
            resultList.add(poll.val);
        }
        treeNodes.addAll(treeNodeQueue);
        return resultList;
    }
}
